package org.smart4j.framework.utils;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.helper.BeanHelper;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author chen
 * @version V1.0
 * @date 2017/9/27
 */
public class IocHelper {

    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (!beanMap.isEmpty()) {
            for (Map.Entry<Class<?>, Object> mapObj : beanMap.entrySet()) {
                // 从map中获取bean类bean实例
                Class<?> beanClass = mapObj.getKey();
                Object beanInstance = mapObj.getValue();
                // 获取bean类中的所有成员变量
                Field[] declaredFields = beanClass.getDeclaredFields();
                if (null != declaredFields && declaredFields.length > 0) {
                    for (Field beanField : declaredFields) {
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            Class<?> type = beanField.getType();
                            Object beanFieldInstance = beanMap.get(type);
                            if (beanFieldInstance != null) {
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }

                        }

                    }
                }


            }

        }
    }
}
